package com.ironman.mes.websocket;

import lombok.extern.slf4j.Slf4j;
import org.noear.solon.net.annotation.ServerEndpoint;
import org.noear.solon.net.websocket.WebSocket;
import org.noear.solon.net.websocket.WebSocketListener;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * ws://localhost:18080/ws/admin?token=1234
 */
@Slf4j
@ServerEndpoint("/ws/{id}")
public class WebSocketEndpoint implements WebSocketListener {

    @Override
    public void onOpen(WebSocket socket) {
        //path var
        String id = socket.param("id");
        //query var
        String token = socket.param("token");

        if (!("admin".equals(id) && "1234".equals(token))) {
            socket.close();
            return;
        }
        log.info("onOpen {}", id);
    }

    @Override
    public void onMessage(WebSocket socket, String text) throws IOException {
        log.info("服务收到的消息: {}", text);
        socket.send("我收到了：" + text);
    }

    @Override
    public void onMessage(WebSocket socket, ByteBuffer binary) throws IOException {

    }

    @Override
    public void onClose(WebSocket socket) {
        log.info("onClose");
    }

    @Override
    public void onError(WebSocket socket, Throwable error) {
        log.info("onError", error);
    }
}